<?php

namespace app\common\command;

use addons\shopro\service\Wallet as WalletService;
use app\common\model\shopro\UserHuzhuLogModel;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\exception\HttpResponseException;

class Huzhu extends Command
{
    protected function configure()
    {
        $this->setName('huzhu')->setHelp('互助奖励')->setDescription('互助奖励');
    }

    protected function execute(Input $input, Output $output)
    {
        $is_release = config('site.is_release');
        if ($is_release == 1) {
            ini_set('memory_limit', "-1");
            $huzhuModel = new UserHuzhuLogModel();
            $userModel  = new User();
            $data       =  $huzhuModel->where(['status'=>1])->whereTime('createtime', 'd')->select();
            if ($data) {
                Db::startTrans();
                try {
                    foreach ($data as $key=>$val){
                        $userData     = $userModel->where(['parent_user_id' => $val->user_id,'score'=>['gt',0]])->field('id,score,is_lock,is_frozen')->select();
                        if($userData){
                            $release = $val->release/count($userData);
                            $release = bcmul($release, '0.1',2);
                            foreach ($userData as $k=>$v){
                                if($v->is_lock == 1 || $v->is_frozen == 1){

                                }else{
                                    if($release > $v->score){
                                        $release =  $v->score;
                                    }
                                    $jian_score = $release;
                                    WalletService::change($v->id, 'score', -$jian_score, 'huzhu',[], '互助奖释放');
                                    $gold      = bcmul($jian_score, $val->golen_scale, 2);//金币
                                    WalletService::change($v->id, 'gold', $gold, 'release_gold_huzhu', [], '互助奖励');
                                    $slive       = bcmul($jian_score, $val->slive_scale, 2);//银币
                                    WalletService::change($v->id, 'silver', $slive, 'release_slive_huzhu',[],'互助奖励');
                                }

                            }
                        }
                        $val->status = 2;
                        $val->save();
                    }
                    Db::commit();
                } catch (HttpResponseException $e) {
                    Db::rollback();
                    $data    = $e->getResponse()->getData();
                    $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                    echo $message;
                }
            } else {
                echo "今日已释放";
            }
        }
    }
}
